package com.seari.main.line17;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.seari.bean.iec104.DiData;
import com.seari.service.DiDataService;
import com.seari.utils.JedisPoolUtils;

import redis.clients.jedis.Jedis;

//@Component
//@Order(value = 2)
public class DumpPoint implements ApplicationRunner
{
	@Autowired
	private DiDataService diDataService;

	@Override
	public void run(ApplicationArguments args) throws Exception
	{
		// TODO Auto-generated method stub
		String key = "line17_DI";
		List<DiData> diDatas = diDataService.getDiDataInfo();
		List<DiData> result = diDatas.stream().filter(data -> data.getPid() > 95096).collect(Collectors.toList());
		Jedis jedis = JedisPoolUtils.getJedis();
		for (DiData data : result)
		{
			String val1 = jedis.hget(key, data.getPoint()+"");
			if(data.getReverse() == 1)
			{
				int temp = Integer.parseInt(val1);
				temp = (temp == 0) ? 1 : 0;
				val1 = temp +"";
			}
			appendToTxt(data.getDesc() + "\t" + data.getPoint() + "\t" + val1);
			if(null != data.getPoint2() && data.getPoint2() > 0)
			{
				String val2 = jedis.hget(key, data.getPoint2()+"");
				appendToTxt(data.getDesc() + "点号2\t" + data.getPoint2() + "\t" + val2);
			}
		}
		
		JedisPoolUtils.close(jedis);
		System.out.println("txt write finished");
	}

	public void appendToTxt(String content)
	{
		FileWriter fw = null;
		try
		{
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("D:\\dd.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println(content);
		pw.flush();
		try
		{
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

}
